package com.settlement.system.service.impl;

import com.settlement.system.common.enums.WpTypeEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.common.util.common.DictionaryUtil;
import com.settlement.system.common.util.common.FasUtil;
import com.settlement.system.mapper.*;
import com.settlement.system.model.entity.common.WpSummary;
import com.settlement.system.service.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 唯品汇总
 * @author user
 */
@Slf4j
@Service
public class WpSummaryServiceImpl extends BaseServiceImpl implements IWpSummaryService {

    @Resource
    private WpSummaryMapper wpSummaryMapper;

    @Resource
    private TblWpBillSaleDetailMapper tblWpBillDetailMapper;

    @Resource
    private TblWpBillDiscountDetailMapper tblWpBillDiscountDetailMapper;

    @Resource
    private TblWpManualItemDiffMapper tblWpManualItemDiffMapper;

    @Resource
    private ITblWpBillSaleDetailService iTblWpBillDetailService;

    @Resource
    private ITblWpBillReturnDetailService iTblWpBillReturnDetailService;

    @Resource
    private ITblWpBillOtherDetailService iTblWpBillOtherDetailService;

    @Resource
    private ITblWpBillDiscountDetailService iTblWpBillDiscountDetailService;

    @Resource
    private ITblWpManualItemDiffService iTblWpManualItemDiffService;

    @Resource
    private ITblWpItemDiffSourceService iTblWpItemDiffSourceService;

    @Resource
    private DictionaryUtil dictionaryUtil;

    /*@Reference(version = "${dubbo.acs.api.version}",timeout = 6000)
    private WpBillDetailApi wpBillDetailApi;

    @Reference(version = "${dubbo.acs.api.version}",timeout = 6000)
    private WpBillDiscountApi wpBillDiscountApi;

    @Reference(version = "${dubbo.acs.api.version}",timeout = 6000)
    private WpManualItemDiffApi wpManualItemDiffApi;

    @Reference(version = "${dubbo.acs.api.version}",timeout = 6000)
    private WpItemDiffApi wpItemDiffApi;*/

    @Override
    public BaseMapper init() {
        return wpSummaryMapper;
    }

    /**
     * 获取底部汇总
     * @param params
     * @return
     * @throws ServiceException
     */
    @Override
    public WpSummary selectFoot(Map<String, Object> params) throws ServiceException {
        try {
            return wpSummaryMapper.selectFoot(params);
        } catch (Exception ex){
            throw new ServiceException("唯品汇总异常",ex);
        }
    }

    /**
     * 更新状态
     * @param summary
     * @throws ServiceException
     */
    @Override
    public void updateProcessStatus(WpSummary summary) throws ServiceException {
        if(!StringUtils.isEmpty(summary.getBillNumber())){
            String[] strings = summary.getBillNumber().split(",");
            for(int index = 0;index < strings.length;index++){
                /*WpParam param = new WpParam(null,strings[index]);
                wpBillDetailApi.asyncSupplement(param);
                wpBillDiscountApi.asyncSupplement(param);
                wpManualItemDiffApi.asyncSupplement(param);*/
            }
        }
    }

    /**
     * 签收
     * @param summary
     * @return
     * @throws ServiceException
     */
    @Override
    public String sign(WpSummary summary) throws ServiceException {
        try {
            String[] billDetailTypes = summary.getBillDetailType().split(",");
            String orderType = "";
            List<String> billDetailTypeList = new ArrayList<>();
            if(billDetailTypes!=null && billDetailTypes.length>0) {
                billDetailTypeList = Arrays.asList(billDetailTypes);
            }
            if (billDetailTypeList.contains("XS")) {
                orderType += ",1";
            }
            if (billDetailTypeList.contains("KT")) {
                orderType += ",2";
            }
            if (billDetailTypeList.contains("QT")) {
                orderType += ",3";
            }
            if(StringUtils.isNotEmpty(orderType)) {
                orderType = orderType.substring(1);
            }

            String[] billNumbers = summary.getBillNumber().split(",");
            String message = validation(billNumbers,billDetailTypeList);
            if(!StringUtils.isEmpty(message)) {
                return message;
            }

            for(int index = 0;index < billNumbers.length;index++){

                Map<String,Object> params = new HashMap<>(16);
                params.put("billNumber",billNumbers[index]);
                params.put("processStatus", WpTypeEnum.PROCESS_STATUS.full_complete.getNo());
                params.put("orderType",orderType);
                FasUtil.formatInQueryCondition(params, "orderType");

                /*WpParam wpParam = new WpParam(null,billNumbers[index]);
                wpParam.setOrderType(orderType);

                if(billDetailTypeList.size()==0 || StringUtils.isNotEmpty(orderType)){
                    tblWpBillDetailMapper.updateProcessStatus(WpTypeEnum.PROCESS_STATUS.Sign.getNo(),params);
                    wpBillDetailApi.asyncTransfer(wpParam);
                }
                if(billDetailTypeList.size()==0 || billDetailTypeList.contains(WpTypeEnum.PAGE_TAB.HDZK.name())){
                    tblWpBillDiscountDetailMapper.updateProcessStatus(WpTypeEnum.PROCESS_STATUS.Sign.getNo(),params);
                    wpBillDiscountApi.asyncTransfer(wpParam);
                }
                if(billDetailTypeList.size()==0 || billDetailTypeList.contains(WpTypeEnum.PAGE_TAB.CYDY.name())){
                    tblWpManualItemDiffMapper.updateProcessStatus(WpTypeEnum.PROCESS_STATUS.Sign.getNo(),params);
                    wpManualItemDiffApi.asyncTransfer(wpParam);
                }*/
            }
        } catch (Exception ex){
            throw new ServiceException("签收异常",ex);
        }
        return null;
    }

    private Set<String> getOrderTypes(Object orderTypes){
        Set<String> orderTypeSet = new HashSet<>();

        if(orderTypes != null){
            String[] strs = orderTypes.toString().split(",");
            for(int index = 0;index < strs.length;index++){
                orderTypeSet.add(strs[index]);
            }
        }
        if(orderTypeSet.size() == 0){
            orderTypeSet.add("ALL");
        }
        return orderTypeSet;
    }

    /**
     * 删除
     * @param params
     * @return
     * @throws ServiceException
     */
    @Override
    public String doDelete(Map<String,Object> params) throws ServiceException {
        try {

            Set<String> orderTypeSet = getOrderTypes(params.get("orderTypes"));

            String toBeDeletedScheduleId = dictionaryUtil.toBeDeletedScheduleIdInQueryCondition();

            params.put("toBeDeletedScheduleId",toBeDeletedScheduleId);

            if(orderTypeSet.contains(WpTypeEnum.PAGE_TAB.ALL.name()) || orderTypeSet.contains(WpTypeEnum.PAGE_TAB.XS.name())){
                String s = this.doDeleteByParams(iTblWpBillDetailService, params);
                if(StringUtils.isNotEmpty(s)){
                    return s;
                }
            }

            if(orderTypeSet.contains(WpTypeEnum.PAGE_TAB.ALL.name()) || orderTypeSet.contains(WpTypeEnum.PAGE_TAB.KT.name())){
                String s = this.doDeleteByParams(iTblWpBillReturnDetailService, params);
                if(StringUtils.isNotEmpty(s)){
                    return s;
                }
            }

            if(orderTypeSet.contains(WpTypeEnum.PAGE_TAB.ALL.name()) || orderTypeSet.contains(WpTypeEnum.PAGE_TAB.QT.name())){
                String s = this.doDeleteByParams(iTblWpBillOtherDetailService, params);
                if(StringUtils.isNotEmpty(s)){
                    return s;
                }
            }

            if(orderTypeSet.contains(WpTypeEnum.PAGE_TAB.ALL.name()) || orderTypeSet.contains(WpTypeEnum.PAGE_TAB.HDZK.name())){
                String s = this.doDeleteByParams(iTblWpBillDiscountDetailService, params);
                if(StringUtils.isNotEmpty(s)){
                    return s;
                }
            }

            if(orderTypeSet.contains(WpTypeEnum.PAGE_TAB.ALL.name()) || orderTypeSet.contains(WpTypeEnum.PAGE_TAB.CY.name())){
                String s = this.doDeleteByParams(iTblWpItemDiffSourceService, params);
                if(StringUtils.isNotEmpty(s)){
                    return s;
                }
            }

            if(orderTypeSet.contains(WpTypeEnum.PAGE_TAB.ALL.name()) || orderTypeSet.contains(WpTypeEnum.PAGE_TAB.CYDY.name())){
                String s = this.doDeleteByParams(iTblWpManualItemDiffService, params);
                if(StringUtils.isNotEmpty(s)){
                    return s;
                }
            }

        } catch (Exception ex){
            log.error(ex.getMessage(),ex);
            throw new ServiceException("操作异常",ex);
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public String doDeleteByParams(IBaseService baseService, Map<String,Object> params) throws ServiceException {
        boolean b = checkService(baseService);
        if(!b){
            return "非指定模块";
        }

        String toBeDeletedScheduleId = (String) params.get("toBeDeletedScheduleId");

        params.put("notScheduleIds",toBeDeletedScheduleId);
        Integer notToBeDeleted = baseService.selectCount(params);
        if(notToBeDeleted>0){
            return "非指定档期ID不允许删除";
        }

        params.remove("notScheduleIds");
        params.put("scheduleIds",toBeDeletedScheduleId);
        Integer toBeDeleted = baseService.selectCount(params);
        log.info("toBeDeleted="+toBeDeleted);
        if(toBeDeleted==0){
            return null;
        }
        Integer toBeDeletedInTransaction = baseService.deleteByParams(params);
        log.info("toBeDeletedInTransaction="+toBeDeletedInTransaction);
        if(!toBeDeletedInTransaction.equals(toBeDeleted)){
            throw new ServiceException("数量校验异常");
        }
        return null;
    }

    boolean checkService(IBaseService baseService){
        boolean b = baseService instanceof ITblWpBillSaleDetailService ||
                baseService instanceof ITblWpBillReturnDetailService ||
                baseService instanceof ITblWpBillOtherDetailService ||
                baseService instanceof ITblWpBillDiscountDetailService ||
                baseService instanceof ITblWpItemDiffSourceService ||
                baseService instanceof ITblWpManualItemDiffService;
        return b;
    }

    /**
     * 下载数据
     * @param vendorCodes
     * @throws ServiceException
     */
    @Override
    public void download(List<String> vendorCodes) throws ServiceException {
        try {
            for(String vendorCode:vendorCodes){
                /*WpParam wpParam = new WpParam(vendorCode,null);
                wpBillDetailApi.asyncDownload(wpParam);
                wpBillDiscountApi.asyncDownload(wpParam);
                wpItemDiffApi.asyncDownload(wpParam);*/
            }
        } catch (Exception ex){
            throw  new ServiceException("下载异常",ex);
        }
    }

    public String validation(String[] billNumbers,List<String> billDetailTypeList) throws ServiceException {
        for (int index = 0;index < billNumbers.length;index++){
            Map<String,Object> params = new HashMap<>(16);
            params.put("billNumber", FasUtil.formatInQueryCondition(billNumbers[index]));
            params.put("processStatus", FasUtil.formatInQueryCondition(WpTypeEnum.PROCESS_STATUS.fulling.getNo()));

            if(billDetailTypeList.size()==0 || billDetailTypeList.contains(WpTypeEnum.PAGE_TAB.XS.name())){
                params.put("orderType",WpTypeEnum.ORDER_TYPE.SALE.getNo());
                if(tblWpBillDetailMapper.selectCount(params) > 0){
                    return billNumbers[index] +  ":销售明细有未匹配的数据,不能签收";
                }
            }
            if(billDetailTypeList.size()==0 || billDetailTypeList.contains(WpTypeEnum.PAGE_TAB.KT.name())){
                params.put("orderType",WpTypeEnum.ORDER_TYPE.RETURN.getNo());
                if(tblWpBillDetailMapper.selectCount(params) > 0){
                    return billNumbers[index] + "客退明细有未匹配的数据,不能签收";
                }
            }
            if(billDetailTypeList.size()==0 || billDetailTypeList.contains(WpTypeEnum.PAGE_TAB.QT.name())){
                params.put("orderType",WpTypeEnum.ORDER_TYPE.OTHER.getNo());
                if(tblWpBillDetailMapper.selectCount(params) > 0){
                    return billNumbers[index] + "其他明细有未匹配的数据,不能签收";
                }
            }
            if(billDetailTypeList.size()==0 || billDetailTypeList.contains(WpTypeEnum.PAGE_TAB.HDZK.name())) {
                params.put("orderType", WpTypeEnum.ORDER_TYPE.DISCOUNT.getNo());
                if (tblWpBillDiscountDetailMapper.selectCount(params) > 0) {
                    return billNumbers[index] + "折扣明细有未匹配的数据,不能签收";
                }
            }
            if(billDetailTypeList.size()==0 || billDetailTypeList.contains(WpTypeEnum.PAGE_TAB.CYDY.name())){
                params.put("orderType",WpTypeEnum.ORDER_TYPE.DIFF.getNo());
                if(tblWpManualItemDiffMapper.selectCount(params) > 0){
                    return billNumbers[index] + "差异明细有未匹配的数据,不能签收";
                }
            }
        }
        return null;
    }

}
